package com.wasin.server.quarter;

import com.diboot.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ 作者： wasin
 * @ 创建时间： 2021/9/26  9:56
 * @ 说明：    定时任务配置
 * @ 当前版本:  1.0.0
 */
@Component
@Slf4j
public class TaskScheduler {

    @Resource
    private Scheduler scheduler;


    /**
     * 设置任务的执行时间
     *
     * @param cron    定时任务表达式
     * @param taskId  任务id
     * @param content 任务内容
     * @param job
     * @throws SchedulerException
     */
    public  void setTaskExecuteDate(String cron, String taskId, String content, Class<TaskJob> job) throws SchedulerException {
        log.info("设置任务的执行时间 taskId={}", taskId);
        Trigger.TriggerState jobState = getJobState(taskId);
        if (!"NONE".equals(jobState.toString())) {
            throw new BusinessException("当前任务名称已存在，任务状态：" + transferredState(jobState));
        }
        //构建定时任务执行体  TaskJob.class 是哪个类去执行这个任务
        JobDetail jobDetail = JobBuilder.newJob(job).withIdentity(JobKey.jobKey(taskId)).build();
        //2020-9-18 18:18:18秒执行这个任务 "18 18 18 18 9 ? 2020"
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        //往任务中传递的参数
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("taskId", taskId);
        jobDataMap.put("content", content);
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(taskId)
                .usingJobData(jobDataMap).withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    /**
     * 删除定时任务
     *
     * @param taskId 定时任务id
     */
    public void delJob(String taskId) throws SchedulerException {
        Trigger.TriggerState jobState = getJobState(taskId);
        if ("NONE".equals(jobState.toString())) {
            throw new BusinessException("当前任务无法删除，任务状态：" + transferredState(jobState));
        }
        JobKey jobKey = JobKey.jobKey(taskId);
        scheduler.deleteJob(jobKey);
    }

    /**
     * 更新定时任务  更新后状态如果是暂停 第一次更新时 会执行一次
     *
     * @param taskId
     */
    public void updateJob(String cron, String taskId, String content) throws SchedulerException {
        Trigger.TriggerState jobState = getJobState(taskId);
        if ("NONE".equals(jobState.toString())) {
            throw new BusinessException("当前任务不存在，任务状态：" + transferredState(jobState));
        }
        //2020-9-18 18:18:18秒执行这个任务 "18 18 18 18 9 ? 2020"
        //构建新的任务表达式
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        //获取任务执行的触发器
        TriggerKey triggerKey = TriggerKey.triggerKey(taskId);
        //获取之前的任务表达式对象
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
       // String cronExpression = trigger.getCronExpression();
        JobDataMap jobDataMap = trigger.getJobDataMap();
        jobDataMap.put("content", content);
        jobDataMap.put("content2", "222");
        //重新构建新的任务触发器
        trigger = trigger.getTriggerBuilder().usingJobData(jobDataMap).withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
        scheduler.rescheduleJob(triggerKey, trigger);
        if ("PAUSED".equals(jobState.toString())) {
            scheduler.pauseJob(JobKey.jobKey(taskId));
        }
    }


    /**
     * 暂停定时任务
     *
     * @param taskId 定时任务id
     */
    public void pauseJob(String taskId) throws SchedulerException {
        Trigger.TriggerState jobState = getJobState(taskId);
        if (!"NORMAL".equals(jobState.toString())) {
            throw new BusinessException("当前任务无法暂停，任务状态：" + transferredState(jobState));
        }
        JobKey jobKey = JobKey.jobKey(taskId);
        scheduler.pauseJob(jobKey);
    }

    /**
     * 恢复定时任务
     *
     * @param taskId 定时任务id
     */
    public void resumeJob(String taskId) throws SchedulerException {
        Trigger.TriggerState jobState = getJobState(taskId);
        if (!"PAUSED".equals(jobState.toString())) {
            throw new BusinessException("当前任务无法恢复，任务状态：" + transferredState(jobState));
        }
        JobKey jobKey = JobKey.jobKey(taskId);
        scheduler.resumeJob(jobKey);
    }

    /**
     * 获取当前定时任务的执行状态
     *
     * @return BLOCKED  阻塞,COMPLETE  完成, ERROR  错误, NONE  不存在, NORMAL 正常, PAUSED 暂停
     */
    public Trigger.TriggerState getJobState(String taskId) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(taskId);
        return scheduler.getTriggerState(triggerKey);
    }


    /**
     * 转义任务状态
     *
     * @param triggerKey
     * @return
     */
    public static String transferredState(Trigger.TriggerState triggerKey) {
        String rs = "正常";
        switch (triggerKey.toString()) {
            case "BLOCKED":
                rs = "阻塞";
                break;
            case "COMPLETE":
                rs = "完成";
                break;
            case "ERROR":
                rs = "错误";
                break;
            case "NONE":
                rs = "任务不存在";
                break;
            case "PAUSED":
                rs = "暂停";
                break;
            default:
                break;
        }
        return rs;

    }


}
